package topic

import (
	"community-service/cmd/api/internal/models/model"
	"community-service/cmd/api/internal/svc"
	"community-service/cmd/api/internal/types"
	e "community-service/pkg/errorx"
	"context"
	"github.com/pkg/errors"
	"google.golang.org/grpc/codes"
	"gorm.io/gorm"

	"github.com/zeromicro/go-zero/core/logx"
)

type CreateTopicLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewCreateTopicLogic(ctx context.Context, svcCtx *svc.ServiceContext) *CreateTopicLogic {
	return &CreateTopicLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *CreateTopicLogic) CreateTopic(req *types.TopicCreateReq) (resp *types.Empty, err error) {

	// 检查专栏是否存在
	menuQuery := l.svcCtx.DB.WithContext(l.ctx).Model(&model.CsCommunityMenu{})
	var existMenu model.CsCommunityMenu
	if err = menuQuery.Session(&gorm.Session{}).Where("id = ?", req.Id).First(&existMenu).Error; err != nil {
		if errors.Is(err, gorm.ErrRecordNotFound) {
			return nil, e.NewGrpcErr(codes.NotFound, e.MenuNotFound)
		}
		return nil, e.NewGrpcErr(codes.Internal, e.DBError)
	}

	// 检查话题名称在该专栏下是否重复
	topicQuery := l.svcCtx.DB.WithContext(l.ctx).Model(&model.CsCommunityTopic{})
	var existTopic model.CsCommunityTopic
	if err = topicQuery.Session(&gorm.Session{}).Where("name = ? AND menu_id = ?", req.Name, req.Id).Find(&existTopic).Error; err != nil {
		return nil, e.NewGrpcErr(codes.Internal, e.DBError)
	}

	if existTopic.ID != 0 {
		return nil, e.NewGrpcErr(codes.AlreadyExists, e.TopicNameEmpty) // 可以添加专门的话题名称重复错误码
	}

	// 创建话题
	newTopic := &model.CsCommunityTopic{
		Name:        req.Name,
		ImageURL:    req.ImageUrl,
		Description: req.Description,
		MenuID:      req.Id,
		Type:        req.Type,
	}

	if err = topicQuery.Create(newTopic).Error; err != nil {
		return nil, e.NewGrpcErr(codes.Internal, e.DBError)
	}

	return &types.Empty{}, nil
}
